package com.tencent.apps.ui.fragment;

import java.util.ArrayList;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.params.HttpParams;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.tencent.apps.R;
import com.tencent.apps.bean.AppInfo;
import com.tencent.apps.bean.Home;
import com.tencent.apps.global.AppsApplication;
import com.tencent.apps.http.HttpHelper;
import com.tencent.apps.http.Url;
import com.tencent.apps.ui.activity.AppDetailActivity;
import com.tencent.apps.ui.adapter.HomeAdaper;
import com.tencent.apps.ui.adapter.HomePagerAdapter;
import com.tencent.apps.utils.CommonUtil;
import com.tencent.apps.utils.GsonUtil;
import com.tencent.apps.utils.LogUtil;

import android.R.integer;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class HomeFragment extends BaseFragment {

	protected static final String TAG = "HomeFragment";

	// 抽取在了baseFragment中
	// @Override
	// public View onCreateView(LayoutInflater inflater, ViewGroup container,
	// Bundle savedInstanceState) {
	//
	// ContentPager contentPager = new ContentPager(getActivity()) {
	//
	// @Override
	// public Object loadData() {
	// return new String("应用宝好");
	// }
	//
	// @Override
	// public View createView() {
	// TextView view = new
	// TextView(AppsApplication.getContext());//getActivity()
	// view.setText("应用宝应用宝");
	// return view;
	// }
	// };
	//
	// return contentPager;
	// }

	ArrayList<AppInfo> list = new ArrayList<AppInfo>();
	ArrayList<String> urlList = new ArrayList<String>();
	Home home = null;

	private HomeAdaper<AppInfo> adapter;

	private ListView listView;

	private HomePagerAdapter homePagerAdapter;

	private PullToRefreshListView refreshListView;
	private ViewPager homePager;
	
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			homePager.setCurrentItem(homePager.getCurrentItem()+1);//接收到消息后，移动到下一行
			handler.sendEmptyMessageAtTime(0, 1000);
		};
	};

	// new OnRefreshListener2() {}???
	@Override
	protected View getSuccessView() {
		initRefreshListView();

		initHeadView();
		adapter = new HomeAdaper<AppInfo>(list, context);
		listView.setAdapter(adapter);
		return refreshListView;// 若返回listview也就报错：nosave。。。2个parent
	}

	public void initRefreshListView() {
		refreshListView = (PullToRefreshListView) View
				.inflate(getActivity(), R.layout.ptr_listview, null);
		refreshListView.setMode(Mode.BOTH);// 设置可刷新的模式

		refreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if (refreshListView.getCurrentMode() == Mode.PULL_FROM_START) {
					// 下拉刷新，不做处理,直接完成刷新，要在主线程
					CommonUtil.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							refreshListView.onRefreshComplete();
						}
					});
				} else {// 上拉加载更多
					contentPager.loadAndRefreshData();
				}
			}
		});

		listView = refreshListView.getRefreshableView();
		listView.setDividerHeight(0);
		listView.setSelector(android.R.color.transparent);// 选中item的颜色
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				LogUtils.d("###position="+position);
				Intent intent = new Intent(getActivity(), AppDetailActivity.class);
				intent.putExtra("packageName", list.get(position-2).packageName);
				startActivity(intent);
			}
		});
	}

	/**
	 * view viewpager adapter addHeadView()
	 */
	private void initHeadView() {
		View headView = View
				.inflate(context, R.layout.layout_home_header, null);
		homePager = (ViewPager) headView.findViewById(R.id.homePager);
		//动态设置viewpager的高
		int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
		float pagerHight = width/2.65f;
		LayoutParams params = homePager.getLayoutParams();
		params.height = (int) pagerHight;
		homePager.setLayoutParams(params);
		
		
		listView.addHeaderView(headView);
	}

	@Override
	protected Object requestData() {
		String json = HttpHelper.get(Url.HOME+list.size());//
		home = GsonUtil.jsonToBean(json, Home.class);

		if (home != null) {
			urlList.addAll(home.picture);
			//只有第一页index=0 的时候在有轮播图
			if (urlList != null  && urlList.size() > 0) {
				homePagerAdapter = new HomePagerAdapter(urlList, context);
				homePager.setAdapter(homePagerAdapter);
				
				//实现无线循环
//				homePager.setCurrentItem(urlList.size()*10000);
			}
			//这个方法requestData（）在子线程中进行，因为loadData(),所以报错
			CommonUtil.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					adapter.notifyDataSetChanged();
					refreshListView.onRefreshComplete();
				}
			});
			
			list.addAll(home.list);
			// list = home.list;
		}
		return home;
	}

	//开始发送消息
//	@Override
//	public void onResume() {
//		super.onResume();
//		handler.sendEmptyMessageAtTime(0, 1000);
//	}
//	//移除消息
//	@Override
//	public void onDestroyView() {
//		super.onDestroyView();
//		handler.removeMessages(0);
//	}
	// 这里即使请求到了数据，返回也是null，因为回调RequestCallBack的耗时，回调还没完成的时候就执行了return
	// list语句，而list = Null(初始化)
	// @Override
	// protected Object requestData() {
	// HttpUtils httpUtils = new HttpUtils();
	// // RequestParams params = new RequestParams(Url.HOME);//???
	// //返回的必须是json数据，String类型的json数据。
	//
	// httpUtils.send(HttpMethod.POST, Url.HOME, new RequestCallBack<String>() {
	//
	// @Override
	// public void onFailure(HttpException exp, String msg) {
	//
	// }
	//
	// @Override
	// public void onSuccess(ResponseInfo<String> info) {
	// String json = info.result;
	// home = GsonUtil.jsonToBean(json, Home.class);
	// // list = home.list;
	//
	// if (home != null) {
	// // list.addAll(home.list);
	// list = home.list;
	// adapter.notifyDataSetChanged();
	// }
	// }
	// });
	// //这里即使请求到了数据，返回也是null，因为回调RequestCallBack的耗时，回调还没完成的时候就执行了return
	// list语句，而list = Null(初始化)
	// return list;
	// }
}
